package com.zhiqian.serializer;

import com.zhiqian.bean.RpcRequest;
import com.zhiqian.enums.PackageType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
//自定义编码器
public class CommonEncoder extends MessageToByteEncoder {

    private static final int MAGIC_NUMBER=0xCAFEBABE;
    private final CommonSerializer serializer;

    public CommonEncoder(CommonSerializer serializer){
        this.serializer=serializer;
    }

    //发送消息进行编码
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        out.writeInt(MAGIC_NUMBER);//标识一个协议包
        if (msg instanceof RpcRequest){
            out.writeInt(PackageType.REQUEST_PACK.getCode());//标明这是调用请求还是响应
        }else{
            out.writeInt(PackageType.RESPONSE_PACK.getCode());
        }
        out.writeInt(serializer.getCode());//标明实际数据使用的序列化器
        byte[] bytes=serializer.serialize(msg);
        out.writeInt(bytes.length);//标明实际数据的字节长度，为了防止粘包
        out.writeBytes(bytes);//发送实际数据
    }
}
